!> author: 左志华
!> date: 2022-07-20
!>
!> Pre/Post-process the data <br>
!> 前后处理
module sph

    use seakeeping_filesystem, only: operator(.join.)
    use seakeeping_error_handling, only: fatal_error
    use sph_command_line, only: pre_settings_t, post_settings_t
    use sph_region_type, only: region_t
    use sph_save_h5part, only: save_h5part
    use sph_load_h5part, only: load_h5part
    use sph_load_lua, only: load_lua_script
    use sph_terminal, only: info, error
    implicit none
    private

    public :: cmd_pre, cmd_post

contains

    !> Pre process the data <br>
    !> 前处理数据
    subroutine cmd_pre(cmd_settings, region)
        type(pre_settings_t), intent(in) :: cmd_settings    !! Pre process settings <br>
                                                            !! 前处理设置
        type(region_t), intent(out) :: region               !! Region <br>
                                                            !! 粒子域
        select case (cmd_settings%type)
        case ("lua", "LUA")
            write (*, '(a)') info('前处理：加载 lua 脚本')
            call load_lua_script(cmd_settings%working_dir.join.'pif.lua', region)

        case default
            call fatal_error("不支持的前处理类型："//cmd_settings%type)

        end select

        write (*, '(a)') info('前处理：保存 h5part 文件')
        call save_h5part(cmd_settings%working_dir.join.'pif.h5part', region, cmd_settings%skip)

    end subroutine cmd_pre

    !> Post process for the results of the simulation <br>
    !> 对结果的后期处理
    subroutine cmd_post(cmd_settings, region)
        use seakeeping_filesystem, only: is_exist
        use sph_save_vtk, only: save_vtk
        use sph_terminal, only: input
        type(post_settings_t), intent(in) :: cmd_settings   !! Post process settings <br>
                                                            !! 后期处理设置
        type(region_t), intent(out) :: region               !! Region <br>
                                                            !! 计算域
        logical :: cover

        select case (cmd_settings%type)
        case ("vtk", "VTK")
            if (is_exist(cmd_settings%working_dir.join.'pif1.vtu') .and. .not. cmd_settings%skip) then
                write (*, '(a)', advance='no') input('文件已存在，将覆盖原文件？(T/F)：')
                read (*, *) cover
                if (.not. cover) return
            end if

            write (*, '(a)') info('后处理：加载 h5part 文件')
            write (*, '(a)') info('后处理: 保存 vtk 格式')
            call load_h5part(file=cmd_settings%working_dir.join.'pif-out.h5part', &
                             nml=cmd_settings%working_dir.join.'pif.nml', &
                             vtk=cmd_settings%working_dir, &
                             region=region, &
                             func=save_vtk)

        case default
            call fatal_error('不支持的后处理类型：'//cmd_settings%type)

        end select

    end subroutine cmd_post

end module sph
